import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import 'dd_user_service.dart';

class DDRongcloudService extends GetxService {
  RCIMIWEngine? engine;

  @override
  void onInit() {
    super.onInit();
  }

  Future<void> init() async {
    await initRongcloud(Get.find<DDUserService>().rongCloudKey);
    await connectRongcloud(Get.find<DDUserService>().rongCloudToken);
  }

  Future<void> initRongcloud(String appkey) async {
    RCIMIWEngineOptions options = RCIMIWEngineOptions.create();
    engine = await RCIMIWEngine.create(appkey, options);

    engine?.onConnectionStatusChanged = (RCIMIWConnectionStatus? status) {
      print(status);
    };
  }

  Future<int?> connectRongcloud(String token) async {
    RCIMIWConnectCallback? callback = RCIMIWConnectCallback(
        onDatabaseOpened: (int? code) {},
        onConnected: (int? code, String? userId) {});

    int? ret = await engine?.connect(token, 30, callback: callback);

    engine?.onMessageReceived =
        (RCIMIWMessage? message, int? left, bool? offline, bool? hasPackage) {};

    return ret;
  }

  Future<void> disconnectRongcloud() async {
    await engine?.disconnect(false);
  }

  Future<void> destroyRongcloud() async {
    engine?.destroy();
  }

  Future<void> sendTextMessage(
    String targetId,
    RCIMIWConversationType conversationType,
    String? channelId,
    String text,
  ) async {
    RCIMIWTextMessage? textMessage = await engine?.createTextMessage(
        conversationType, targetId, channelId, text);
    if (textMessage != null) {
      int? code = await engine?.sendMessage(textMessage);
      if (code == 0) {}
    }
  }
}
